package com.cyq.blog.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.cyq.blog.entity.Blog;
import com.cyq.blog.entity.Category;
import com.cyq.blog.entity.Comment;
import com.cyq.blog.service.BlogService;
import com.cyq.blog.service.CategoryService;
import com.cyq.blog.service.CommentService;
import com.cyq.blog.util.MarkDownUtil;
import com.cyq.blog.util.MybatisPlusUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.thymeleaf.expression.Lists;

import java.util.*;

/**
 * BlogController class
 *
 * @author chenyeqing
 * @date 2021/5/13
 */
@Slf4j
@Controller
public class BlogController {

    @Autowired
    private BlogService blogService;

    @Autowired
    private CommentService commentService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 进入首页
     * @return
     */
    @GetMapping({"", "/", "index", "index.html"})
    public String index(Model model) {
        log.info("进入首页=>");
        // 状态为1（发布）
        QueryWrapper<Blog> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("blog_status", 1);
        List<Blog> blogs = blogService.list(queryWrapper);

        // 获取右侧访问量
        blogViews(model);

        log.info("进入首页===blogs===>" + blogs);
        model.addAttribute("blogs", blogs);

        return "index";
    }

    /**
     * 查看具体博客
     * @param urlOrId
     * @param model
     * @return
     */
    @GetMapping("/blog/{urlOrId}")
    public String blogDetail(@PathVariable("urlOrId") String urlOrId, Model model) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("blog_custom_url", urlOrId);
        // 发布状态
         map.put("blog_status", 1);
        QueryWrapper<Blog> blogQueryWrapper = new QueryWrapper(map);
        blogQueryWrapper.allEq(map);
        // 先根据 自定义url 找
        Blog showBlog;
        List<Blog> list = blogService.list(blogQueryWrapper);
        if (list.size() >= 1) {
            // 重复就显示查到的第一条  懒得写查到阅读量最高了
            showBlog = list.get(0);
        } else {
            // 如果没有则根据 ID
            showBlog = blogService.getById(urlOrId);
        }

        // null 的处理方式，暂时为 抛出异常
        Assert.notNull(showBlog, "没有这条记录");
        // 每次访问从redis获取访问量
        Long views = Long.valueOf(stringRedisTemplate.opsForValue().get("/blog/" + urlOrId));
        showBlog.setBlogViews(views);
        // 一定条件就存到数据库 可以变成其他次数，表示多少访问存入数据库
        if (views % 10 < 1) {
            blogService.updateById(showBlog);
        }

        // 评论
        QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
        // 审核已通过
        queryWrapper.eq("comment_status", "1");
        // 对应博客
        queryWrapper.eq("blog_id", showBlog.getBlogId());
        // 倒序显示
        queryWrapper.orderByDesc("comment_create_time");
        List<Comment> commentList = commentService.list(queryWrapper);
        log.info("commentList=>" + commentList);

        String blogContent = showBlog.getBlogContent();
        // 显示本地
        // 左括号开头 中间任意字符，assets\ 结尾，替换成 img
        String zz = "[(].*assets\\\\";
        String s = blogContent.replaceAll(zz, "(img/");
        showBlog.setBlogContent(MarkDownUtil.mdToHtml(s));
        model.addAttribute("blog", showBlog);
        model.addAttribute("commentList", commentList);
        return "blog/blogDetail";
    }


    @GetMapping("/blog/search")
    public String searchBlog(String searchBlogTitle, Model model) {
        log.info("searchBlogTitle=>" + searchBlogTitle);

        QueryWrapper<Blog> blogQueryWrapper = new QueryWrapper<>();

        if (StringUtils.hasText(searchBlogTitle)) {
            blogQueryWrapper.like("blog_title", searchBlogTitle);
        }
        List<Blog> blogs = blogService.list(blogQueryWrapper);

        // 获取右侧访问量
        blogViews(model);

        log.info("进入首页===blogs===>" + blogs);
        model.addAttribute("blogs", blogs);


        return "index";
    }


    /**
     * 获取右侧的访问量排行榜
     */
    public void blogViews(Model model) {
        QueryWrapper<Blog> blogQueryWrapper = new QueryWrapper<>();
        blogQueryWrapper.eq("blog_status", 1);
        blogQueryWrapper.orderByDesc("blog_views");
        // 倒序查出所有
        List<Blog> blogs1 = blogService.list(blogQueryWrapper);

        // 更新首页的阅读量
        for (Blog blog : blogs1) {
            // redis中有值就用redis中的阅读量，没有就用数据库中的
            String s = stringRedisTemplate.opsForValue().get("/blog/" + blog.getBlogId());
            if (StringUtils.hasText(s)) {
                Long views = Long.valueOf(s);
                blog.setBlogViews(views);
            }
        }

        model.addAttribute("blogsViews", blogs1);
    }


}
